package com.ogawa.base.widget;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ValueAnimator;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.view.animation.AccelerateInterpolator;

import androidx.core.content.ContextCompat;

import com.ogawa.base.R;

import me.jessyan.autosize.utils.AutoSizeUtils;


/**
 * Created by huangyoulin on 2018/7/17.
 * description:
 */

public class CarDashboardView extends View {
    String TAG = "CarDashboardView";
    // 起始角度
    private int mStartAngle = 40;
    // 绘制角度
    private int mEndAngle = 320;

    private int width;
    private int height;


    // 最小值
    private float mMinValue = 0;
    // 最大值
    private float mMaxValue = 100;
    // 实时速度
    private float value = 50;
    private float oldValue = value;


    private int mPadding;
    private Paint mPaint;
    private ValueAnimator valueAnimator;

    public CarDashboardView(Context context) {
        this(context, null);
    }

    public CarDashboardView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public CarDashboardView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }


    //仪表盘颜色
    private int dialColor = Color.RED;
    private String title = "酸痛百分比";

    private int valueSp = 100;
    private int baifenbiSp = 30;
    private int valueTitleSp = 35;
    private float baifenbi = 1f;

    //最外环画笔的宽度
    private int externalPaintWidth = 2;
    //外圆与内圆间隔
    private int intervalSmallLength = 10;
    private int intervalStartLength = 20;
    private int externalRadius;
    private int outArcWidth = 5;//外圈的宽度
    private int outArcValueWidth = 10;//外圈的宽度
    private int outArcLess = 3;//外圈距离边框的大小
    private int mStrokeWidth = 3; // 画笔宽度


    public void setDialColor(int dialColor) {
        this.dialColor = dialColor;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    private void init() {
        mStrokeWidth = dp2px(mStrokeWidth);
        externalPaintWidth = dp2px(externalPaintWidth);
        intervalSmallLength = dp2px(intervalSmallLength);
        intervalStartLength = dp2px(intervalStartLength);
        outArcWidth = dp2px(outArcWidth);
        outArcValueWidth = dp2px(outArcValueWidth);
        outArcLess = dp2px(outArcLess);
        valueSp = sp2px(valueSp);
        baifenbiSp = sp2px(baifenbiSp);
        valueTitleSp = sp2px(valueTitleSp);

        mPaint = new Paint();
        mPaint.setAntiAlias(true);

    }

    private void reinitSizeBybaifenbi(){
        if (baifenbi>0){
            externalPaintWidth = (int) (externalPaintWidth/baifenbi);
            mStrokeWidth = (int) (mStrokeWidth/baifenbi);
            intervalSmallLength = (int) (intervalSmallLength/baifenbi);
            intervalStartLength = (int) (intervalStartLength/baifenbi);
            outArcWidth = (int) (outArcWidth/baifenbi);
            outArcValueWidth = (int) (outArcValueWidth/baifenbi);
            outArcLess = (int) (outArcLess/baifenbi);
            valueSp = (int) (valueSp/baifenbi);
            baifenbiSp = (int) (baifenbiSp/baifenbi);
            valueTitleSp = (int) (valueTitleSp/baifenbi);
        }


    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);

        mPadding = Math.max(
                Math.max(getPaddingLeft(), getPaddingTop()),
                Math.max(getPaddingRight(), getPaddingBottom())
        );
        setPadding(mPadding, mPadding, mPadding, mPadding);
        int width = resolveSize(getWidth(), widthMeasureSpec);
        externalRadius = (width - mPadding * 2 - mStrokeWidth * 2) / 2;

        int height = externalRadius * 2 + mStrokeWidth * 2;
        setMeasuredDimension(width, height + getPaddingTop() + getPaddingBottom());
    }

    @Override
    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
        super.onLayout(changed, left, top, right, bottom);
        baifenbi = dp2px(375) / getWidth();
        reinitSizeBybaifenbi();
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        width = w;
        height = h;
    }

    Rect mValueRect = new Rect();
    Rect mbaifenRect = new Rect();
    Rect mTitleRect = new Rect();

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        float rAngle = (mEndAngle - mStartAngle) / mMaxValue;
//        canvas.drawColor(Color.parseColor("#3FC5FD"));
        mPaint.setStyle(Paint.Style.STROKE);
        mPaint.setStrokeWidth(outArcWidth);
        mPaint.setColor(ContextCompat.getColor(getContext(), R.color.color_white_bg));
        //绘制外圈
        int less = dp2px(outArcLess);
        canvas.drawArc(getLeft() + less, getTop() + less,
                getRight() - less, getBottom() - less,
                mStartAngle + 90, mEndAngle - mStartAngle,
                false, mPaint);

        mPaint.setStyle(Paint.Style.STROKE);
        mPaint.setStrokeWidth(outArcValueWidth);
        mPaint.setColor(dialColor);
        int less2 = less;
        canvas.drawArc(getLeft() + less2, getTop() + less2,
                getRight() - less2, getBottom() - less2,
                mStartAngle + 90, rAngle * value,
                false, mPaint);

        canvas.translate(width / 2, height / 2);
        int canvasFirstState = canvas.save();
        mPaint.setStyle(Paint.Style.STROKE);
        mPaint.setStrokeWidth(externalPaintWidth);
//        mPaint.setColor(ContextCompat.getColor(getContext(), R.color.picture_color_light_grey));
        //圆点不绘制
//        canvas.drawCircle(0, 0, 10, mPaint);

        //先算出百分比的大小，再整体计算位置
        String valueStr2 = "%";
        mPaint.setTextSize(baifenbiSp);
        mPaint.getTextBounds(valueStr2, 0, valueStr2.length(), mbaifenRect);
        mPaint.setStyle(Paint.Style.FILL);
        mPaint.setColor(Color.WHITE);
        mPaint.setTextSize(valueSp);
        String valueStr = "" + (int) (value);
        mPaint.getTextBounds(valueStr, 0, valueStr.length(), mValueRect);
        canvas.drawText(valueStr, 0 - mValueRect.width() / 2 - mbaifenRect.width() / 2, 0 + mValueRect.height() / 2, mPaint);
        mPaint.setTextSize(baifenbiSp);
        canvas.drawText(valueStr2, (mValueRect.width() - mValueRect.width() / 2),
                0 + mValueRect.height() / 2, mPaint);


        //底下的标题
        if (title != null && title.length()>0){
            mPaint.setTextSize(valueTitleSp);
            mPaint.getTextBounds(title, 0, title.length(), mTitleRect);
            canvas.drawText(title,0-mTitleRect.width()/2,height/2-mTitleRect.height()/2,mPaint);
        }


        canvas.rotate(mStartAngle);

        // 绘制光晕圆形之间的连接线
        mPaint.setStyle(Paint.Style.STROKE);
        for (int i = 0; i <= mMaxValue; i++) {
            if (i <= value) {
                mPaint.setColor(dialColor);
            } else {
                mPaint.setColor(Color.WHITE);
            }
            canvas.drawLine(0, externalRadius - intervalStartLength,
                    0, externalRadius - intervalStartLength - intervalSmallLength, mPaint);

            canvas.rotate(rAngle);
        }

        canvas.restoreToCount(canvasFirstState);
        //指针
//        canvas.drawLine(0,externalRadius - intervalBigLength - pointLingthInterval,
//                0,pointLingthInterval, pointPaint);
//        canvas.restoreToCount(canvasFirstState);
    }

    private int dp2px(int dp) {
        return AutoSizeUtils.dp2px(getContext(), dp);
//        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp,
//                Resources.getSystem().getDisplayMetrics());
    }

    private int sp2px(int sp) {
//        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, sp,
//                Resources.getSystem().getDisplayMetrics());
        return AutoSizeUtils.sp2px(getContext(), sp);
    }

    public float getValue() {
        return value;
    }

    public void setValue(float value) {
        oldValue = this.value;
        this.value = value;
        if (value <= mMinValue) {
            this.value = mMinValue;
        }
        if (value >= mMaxValue) {
            this.value = mMaxValue;
        }
        setValueAnimator(value);

    }


    public void setValueAnimator(final float setValue) {
        if (valueAnimator != null && valueAnimator.isRunning()) {
            valueAnimator.cancel();
        }
        valueAnimator = ValueAnimator.ofFloat(oldValue, setValue);
        AccelerateInterpolator decelerateInterpolator = new AccelerateInterpolator();
        valueAnimator.setInterpolator(decelerateInterpolator);

        valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                CarDashboardView.this.value = (Float) animation.getAnimatedValue();
                invalidate();
            }
        });
        valueAnimator.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                super.onAnimationEnd(animation);
                Log.e(TAG, "onAnimationEnd: ");
                oldValue = setValue;
            }
        });
        valueAnimator.start();
    }

}
